<script>
// 引入vue3 getCurrentInstance
import { getCurrentInstance } from "vue";
import pinia from "@/store/index";
import { useMsgStore } from "@/store/message";
import { useloginStore } from "@/store/login";
import { initSDK } from "./utils/trtc.js";
// #ifdef APP-PLUS
const keepAlive = uni.requireNativePlugin("Ba-KeepAlive");
// #endif
const msgStore = useMsgStore(pinia);
const userStore = useloginStore(pinia);

export default {
  data() {
    return {
      isDownloading: false,
      dataResult: "",
      type: undefined,
      applicationsNum: 0,
      appStatus: true,
      appBadgeNumber: 0,
    };
  },
  onLaunch() {
    // 初始化APP设置
    let setting = uni.getStorageSync("appSetting") ?? "";
    if (!setting) {
      userStore.setAppSetting({
        voiceStatus: true,
        vibrateStatus: false,
        circleAvatar: false,
      });
    } else {
      userStore.setAppSetting(setting);
    }
    // 获取全局配置
    userStore.getGlobalConfig();

    uni.getSystemInfo({
      success: function (e) {
        let paddingB = 0;
        // 获取 appContext  上下文
        const { appContext } = getCurrentInstance();
        appContext.config.globalProperties.StatusBar = e.statusBarHeight;
        // #ifndef MP
        if (e.platform == "android") {
          appContext.config.globalProperties.CustomBars = e.statusBarHeight + 50 + "px";
          appContext.config.globalProperties.CustomBar = e.statusBarHeight + 50;
        } else {
          appContext.config.globalProperties.CustomBars = e.statusBarHeight + 45 + "px";
          appContext.config.globalProperties.CustomBar = e.statusBarHeight + 45;
        }
        // #endif
        // #ifdef MP-WEIXIN

        let custom = wx.getMenuButtonBoundingClientRect();
        appContext.config.globalProperties.Custom = custom;
        appContext.config.globalProperties.CustomBars = custom.bottom + custom.top - e.statusBarHeight + "px";
        appContext.config.globalProperties.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
        // #endif

        // #ifdef MP-ALIPAY
        appContext.config.globalProperties.CustomBars = e.statusBarHeight + e.titleBarHeight + "px";
        appContext.config.globalProperties.CustomBar = e.statusBarHeight + e.titleBarHeight;
        // #endif

        // #ifdef MP
        try {
          var res = uni.getSystemInfoSync();
          res.model = res.model.replace(" ", "");
          res.model = res.model.toLowerCase();
          var res1 = res.model.indexOf("iphonex");
          if (res1 > 5) {
            res1 = -1;
          }
          var res2 = res.model.indexOf("iphone1");
          if (res2 > 5) {
            res2 = -1;
          }
          if (res1 != -1 || res2 != -1) {
            paddingB = uni.upx2px(50);
          }
        } catch (e) {
          return null;
        }
        // #endif
        // #ifdef H5
        paddingB = uni.upx2px(100);
        // #endif
        // 获取设备底部高度
        appContext.config.globalProperties.inlineTools = paddingB;
        // 设置全局底部导航栏高度
        appContext.config.globalProperties.navBarHeight = uni.upx2px(100);
      },
    });

    uni.getPushClientId({
      success: (res) => {
        uni.setStorageSync("cid", res.cid);
      },
      fail(err) {
        console.log(err);
      },
    });
    // 只有app才有推送权限
    // #ifdef APP-PLUS
    uni.onPushMessage((res) => {
      let data = res.data;
      if (res.type == "click") {
        let playload = data.payload;
        let toUser = playload.toContactId ?? "";

        const url = toUser ? `/pages/message/chat?id=${toUser}` : "/pages/index/index";

        uni.navigateTo({
          url: url,
        });
      } else if (res.type == "receive") {
        let appStatus = this.appStatus;
        // 如果app在后台运行,创建通知栏
        if (!appStatus) {
          let message = {
            title: data.title,
            content: data.content,
            payload: data.payload,
          };
          let systemInfo = uni.getSystemInfoSync();
          // 判断平台,如果是安卓就去下载头像并展示头像
          if (systemInfo.platform === "android") {
            uni.downloadFile({
              url: data.payload.fromUser.avatar,
              success: (res) => {
                if (res.statusCode === 200) {
                  message.icon = res.tempFilePath;
                  uni.createPushMessage(message);
                }
              },
            });
          } else if (systemInfo.platform === "ios") {
            uni.createPushMessage(message);
          }
        }
      }
    });
    // #endif
  },
  mounted() {
    // #ifdef APP-PLUS
    setTimeout(() => {
      !this.isDownloading && this.updateVersion();
    }, 5000);

    this.applicationsNum = uni.getStorageSync("applicationsNum") || 0;

    //权限
    !this.applicationsNum && this.requestAllPermissions();

    // plus.navigator.setFullscreen(true); //隐藏状态栏(应用全屏:只能隐藏状态栏，标题栏和虚拟返

    //注册保活
    this.register();

    //是否正在运行
    setInterval(() => {
      this.isRunning();
    }, 60 * 1000);
    // #endif
  },
  onUnload(e) {
    this.scoketClose();
    this.socketIo.traderDetailIndex = 100; // 初始化 tabIndex
  },
  onShow: function () {
    // #ifdef APP-PLUS
    //清空通知
    plus.push.clear();

    //清除角标
    this.appBadgeNumber = 0;
    plus.runtime.setBadgeNumber(this.appBadgeNumber, {
      title: "",
      content: "",
    });
    // #endif

    if (!this.socketIo.checkStatus()) {
      uni.$emit("socketStatus", false);
      this.getWebsocketData();
    }
    this.appStatus = true;
  },
  methods: {
    //版本更新
    updateVersion() {
      plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
        // 通过接口获取最新版本信息
        this.$api.LoginApi.version({
          version: widgetInfo.versionCode ?? "400000",
        }).then((res) => {
          const resData = res.data;
          if (res.code != 0) return;
          if (resData.version <= widgetInfo.versionCode) return;
          let content = "";
          resData.describe.forEach((item, index) => {
            content += `${index + 1}、${item};\n`;
          });

          uni.showModal({
            title: "版本更新",
            content: content,
            showCancel: resData.force ? false : true,
            success: (modalRes) => {
              if (modalRes.confirm) {
                if (resData.type == 0) {
                  // 热更新
                  this.updateHot(resData.download);
                } else {
                  // 整包更新
                  this.updatePackage(resData.download);
                }
              } else if (modalRes.cancel) {
                this.isDownloading = false;
              }
            },
          });
        });
      });
    },
    // 热更新
    updateHot(url) {
      this.isDownloading = true;

      uni.showToast({
        title: "后台下载中...",
        icon: "none",
      });
      uni.downloadFile({
        url,
        success: (downloadResult) => {
          if (downloadResult.statusCode === 200) {
            // 下载更新文件成功后进行安装
            plus.runtime.install(
              downloadResult.tempFilePath,
              {
                force: true, // 是否强制安装, 如果将要安装应用的版本号不高于现有应用的版本号则终止安装，并返回安装失败。
              },
              () => {
                this.isDownloading = false;
                uni.showToast({
                  title: "更新完毕，即将重启",
                  icon: "none",
                  position: "bottom",
                });
                setTimeout(() => {
                  plus.runtime.restart(); // 安装完成后重启应用
                }, 2000);
              },
              (e) => {
                this.isDownloading = false;
                uni.showToast({
                  title: `${e}`,
                  icon: "none",
                  position: "bottom",
                });
              }
            );
          }
        },
        fail: (fails) => {
          uni.showToast({
            title: `${fails.errMsg}`,
            icon: "none",
          });
        },
      });
    },
    // 整包更新
    updatePackage(url) {
      this.isDownloading = true;

      const loading = plus.nativeUI.showWaiting("准备下载");
      // 构建了下载任务，但此时并未开始下载
      const dtask = plus.downloader.createDownload(url, {}, (downloadResult, status) => {
        if (status === 200) {
          plus.runtime.install(
            downloadResult.filename,
            {
              force: true, //是否强制安装
            },
            () => {
              this.isDownloading = false;
              plus.runtime.restart(); // 安装成功后重启
            },
            (e) => {
              this.isDownloading = false;
              uni.showToast({
                icon: "none",
                title: "下载更新失败",
              });
            }
          );
        } else {
          this.isDownloading = false;
          plus.nativeUI.alert("安装失败，请稍候重试: " + status);
        }
      });

      dtask.addEventListener("statechanged", (task) => {
        switch (task.state) {
          case 1:
            loading.setTitle("正在下载");
            break;
          case 2:
            loading.setTitle("已连接到服务器");
            break;
          case 3:
            const pr = Math.floor(((task.downloadedSize || 0) / (task.totalSize || 0)) * 100);
            loading.setTitle(`正在下载 ${pr} %`);
            break;
          case 4:
            plus.nativeUI.closeWaiting();
            break;
        }
      });

      // 执行安装包下载
      dtask.start();
    },
    // 权限数组
    getPermissions() {
      const Manifest = plus.android.importClass("android.Manifest");

      return [
        {
          name: "相机",
          manifest: Manifest.permission.CAMERA,
          description: "需要使用相机权限用于拍照和扫码",
        },
        {
          name: "定位",
          manifest: Manifest.permission.ACCESS_FINE_LOCATION,
          description: "需要定位权限用于获取您的地理位置信息",
        },
        {
          name: "文件管理",
          manifest: Manifest.permission.WRITE_EXTERNAL_STORAGE,
          description: "需要文件管理权限用于保存和读取文件",
        },
        {
          name: "录音",
          manifest: Manifest.permission.RECORD_AUDIO,
          description: "需要录音权限用于语音输入和录音功能",
        },
        {
          name: "通知",
          manifest: Manifest.permission.POST_NOTIFICATIONS, // Android 13 通知权限
          description: "需要通知权限用于接收重要信息",
        },
        {
          name: "后台弹窗",
          manifest: Manifest.permission.SYSTEM_ALERT_WINDOW,
          description: "用于通知栏唤起APP，该权限需要用户自行在【应用信息 - 其他权限】中打开，如已打开该权限，请忽略",
        },
      ];
    },

    // 检查权限是否已授权
    checkPermission(permission) {
      const main = plus.android.runtimeMainActivity();
      const ActivityCompat = plus.android.importClass("androidx.core.app.ActivityCompat");
      const PackageManager = plus.android.importClass("android.content.pm.PackageManager");

      return ActivityCompat.checkSelfPermission(main, permission.manifest) === PackageManager.PERMISSION_GRANTED;
    },
    // 请求单个权限
    requestPermission(permission) {
      const main = plus.android.runtimeMainActivity();
      const ActivityCompat = plus.android.importClass("androidx.core.app.ActivityCompat");
      const Manifest = plus.android.importClass("android.Manifest");

      this.applicationsNum = uni.getStorageSync("applicationsNum") || 0;

      if (!this.checkPermission(permission)) {
        if (permission.manifest === Manifest.permission.SYSTEM_ALERT_WINDOW && this.applicationsNum >= 1) return;

        // 弹出权限作用说明对话框
        plus.nativeUI.confirm(
          `应用需要【${permission.name}】权限。\n作用：${permission.description}`,
          (e) => {
            if (e.index === 0) {
              // 同意授权
              ActivityCompat.requestPermissions(main, [permission.manifest], 0);

              // 针对后台弹窗权限，需要跳转到系统设置界面
              if (permission.manifest === Manifest.permission.SYSTEM_ALERT_WINDOW) {
                uni.setStorageSync("applicationsNum", 1);
                this.requestOverlayPermission();
              }
            } else {
              // 用户拒绝权限
              plus.nativeUI.alert(`${permission.name} 权限被拒绝，相关功能将无法使用`);
            }
          },
          "权限请求",
          ["同意", "拒绝"]
        );
      } else {
        console.log(`${permission.name} 权限已授权`);
      }
    },
    // 请求后台弹窗权限
    requestOverlayPermission() {
      const main = plus.android.runtimeMainActivity();
      const Uri = plus.android.importClass("android.net.Uri");
      const Intent = plus.android.importClass("android.content.Intent");

      const intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
      const packageName = main.getPackageName();
      intent.setData(Uri.parse(`package:${packageName}`));
      main.startActivity(intent);
    },
    // 申请所有权限
    requestAllPermissions() {
      const permissions = this.getPermissions(); // 获取所有权限配置
      permissions.forEach((permission) => {
        this.requestPermission(permission);
      });
    },
    //通知权限
    enablPermission() {
      let main = plus.android.runtimeMainActivity();
      let pkName = main.getPackageName();
      let uid = main.getApplicationInfo().plusGetAttribute("uid");
      let NotificationManagerCompat = plus.android.importClass("android.support.v4.app.NotificationManagerCompat");
      //android.support.v4升级为androidx
      if (NotificationManagerCompat == null) {
        NotificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat");
      }
      let areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
      // 未开通‘允许通知'权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置
      if (!areNotificationsEnabled) {
        uni.showModal({
          title: "通知权限开启提醒",
          content: "您还没有开启通知权限，无法接受到消息通知，请前往设置！",
          showCancel: false,
          confirmText: "去设置",
          success: function (res) {
            if (res.confirm) {
              let Intent = plus.android.importClass("android.content.Intent");
              let Build = plus.android.importClass("android.os.Build");
              //android 8.0引导
              if (Build.VERSION.SDK_INT >= 26) {
                let intent = new Intent("android.settings.APP_NOTIFICATION_SETTINGS");
                intent.putExtra("android.provider.extra.APP_PACKAGE", pkName);
              } else if (Build.VERSION.SDK_INT >= 21) {
                //android 5.0-7.0
                let intent = new Intent("android.settings.APP_NOTIFICATION_SETTINGS");
                intent.putExtra("app_package", pkName);
                intent.putExtra("app_uid", uid);
              } else {
                //(<21)其他--跳转到该应用管理的详情页
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                let uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
                intent.setData(uri);
              }
              // 跳转到该应用的系统通知设置页
              main.startActivity(intent);
            }
          },
        });
      }
    },
    //多个权限统一申请
    checkAndRequestPermissions() {
      this.enablPermission();
      // 检查当前平台是否是 Android
      if (uni.getSystemInfoSync().platform === "android") {
        const main = plus.android.runtimeMainActivity();
        const ContextCompat = plus.android.importClass("androidx.core.content.ContextCompat");
        const ActivityCompat = plus.android.importClass("androidx.core.app.ActivityCompat");
        const PackageManager = plus.android.importClass("android.content.pm.PackageManager");

        const permissions = [
          "android.permission.RECORD_AUDIO",
          "android.permission.CAMERA",
          "android.permission.ACCESS_FINE_LOCATION",
          "android.permission.WRITE_EXTERNAL_STORAGE",
        ];

        const permissionDescriptions = {
          "android.permission.RECORD_AUDIO": "需要使用麦克风录音",
          "android.permission.CAMERA": "需要使用相机拍摄照片",
          "android.permission.ACCESS_FINE_LOCATION": "需要获取当前位置",
          "android.permission.WRITE_EXTERNAL_STORAGE": "需要保存文件到存储卡",
        };

        const permissionsToRequest = [];

        permissions.forEach((permission) => {
          const hasPermission =
            ContextCompat.checkSelfPermission(main, permission) === PackageManager.PERMISSION_GRANTED;
          if (!hasPermission) {
            permissionsToRequest.push(permission);
          }
        });

        if (permissionsToRequest.length > 0) {
          const descriptions = permissionsToRequest.map((permission) => permissionDescriptions[permission]).join("\n");
          uni.showModal({
            title: "权限申请",
            content: `应用需要以下权限：\n${descriptions}`,
            success: (res) => {
              if (res.confirm) {
                ActivityCompat.requestPermissions(main, permissionsToRequest, 0);
              }
            },
          });
        } else {
          console.log("所有权限已授予");
        }
      }
    },

    scoketClose() {
      this.socketIo.connectNum = 1;
      const data = {
        type: "close",
      };
      this.socketIo.send(data); // 这是给后端发送特定数据 关闭推送
      this.socketIo.Close(); // 主动 关闭连接 ， 不会重连
    },
    getWebsocketData() {
      // 获取用户信息
      var userInfo = uni.getStorageSync("userInfo");
      var _this = this;
      // 要发送的数据包
      const data = {
        type: "ping",
      };
      // 打开连接
      this.socketIo.connectSocketInit(data);
      uni.$off("getPositonsOrder");
      // 接收数据,全局监听
      uni.$on("getPositonsOrder", (res) => {
        var userInfo = uni.getStorageSync("userInfo");
        let data = res.data;
        this.connect = true;
        switch (res["type"]) {
          // 服务端ping客户端
          case "ping":
            this.socketIo.send({
              type: "pong",
            });
            break;
          case "pong":
            userStore.$patch({
              multiport: res.multiport,
            });
            break;
          // 登录 更新用户列表
          case "init":
            // 设置全局clientId
            uni.setStorageSync("client_id", res.client_id);
            if (userInfo) {
              this.$api.LoginApi.bindUid({
                client_id: res["client_id"],
                user_id: userInfo.user_id,
                cid: uni.getStorageSync("cid"),
              })
                .then((e) => {
                  userInfo.member_expire = e.data.member_expire ?? 0;
                  uni.setStorageSync("userInfo", userInfo);

                  this.socketIo.send({
                    type: "bindUid",
                    user_id: userInfo.user_id,
                    token: uni.getStorageSync("authToken"),
                  });

                  // 初始化腾讯云音视频SDK
                  initSDK(userInfo.user_id);
                })
                .catch((error) => {});
            }
            break;
          // 上线、下线通知
          case "isOnline":
            msgStore.updateContacts({
              id: data.id,
              is_online: data.is_online,
            });
            break;
          case "silent":
            if (data.is_silent == 0) {
              this.$api.msgApi.initContacts().then((res) => {
                // 设置消息未读数和系统消息未读数
                msgStore.sysUnread = res.count;
                msgStore.initContacts(res.data);
              });
            }
            break;
          case "offline":
            let clientId = uni.getStorageSync("client_id");
            if (data.id == userInfo.user_id && data.client_id != clientId && data.isMobile) {
              uni.showToast({
                title: "您的账号在其他地方登录，已被迫下线！",
                icon: "none",
                duration: 2500,
              });
              userStore.logout();
            }
            break;
          case "simple":
          case "tempChat":
          case "group":
            // #ifdef APP-PLUS
            //创建通知 && 角标数字
            if (!this.appStatus) {
              this.appBadgeNumber++;
              plus.runtime.setBadgeNumber(this.appBadgeNumber, {
                title: data.fromUser?.displayName ?? "新消息",
                content: data.content,
              });

              this.createMessage(data);
            }
            // #endif

            // 只要不是自己发的,才可以播放声音
            if (data.fromUser.id != userInfo.user_id) {
              const contact = msgStore.getContact(data.toContactId);
              // 如果开启了声音才播放
              if (data.toContactId == "system" || (contact.is_notice && contact.is_notice == 1)) {
                this.playSound();
              }
            }
            this.appendMessage(res);
            break;
          case "setChatTop":
            msgStore.updateContacts({
              id: data.id,
              identity: data.identity,
              is_top: data.is_top,
            });
            break;
          case "setIsNotice":
            msgStore.updateContacts({
              id: data.id,
              is_notice: data.is_notice,
            });
            break;
          // 新增加了群聊
          case "addGroup":
            msgStore.appendContacts(data);
            this.$api.LoginApi.bindGroup({
              client_id: uni.getStorageSync("client_id"),
              group_id: data.id,
            });
            break;
          // 群直播状态
          case "live":
            msgStore.updateContacts({
              id: data.group_id,
              live_info: data.status === "live" ? data : 0,
            });
            break;
          // 新增加了临时聊天
          case "tempChat":
            // let contacts = msgStore.contacts;
            // const index = contacts.findIndex((item) => item.id === data.fromUser?.id);

            // if (data.fromUser?.id != userStore.userInfo.id) {
            //   if (index === -1) {
            //     const d = {};
            //     Object.assign(d, data, data.fromUser, {
            //       lastContent: data.content,
            //       tempChat: true,
            //       id: Number(data.fromUser.id)
            //     });
            //     contacts.unshift(d);
            //   } else {
            //     contacts[index]['lastContent'] = data.content;
            //   }
            // }

            // msgStore.initContacts(contacts);
            // 只要不是自己发的,才可以播放声音
            if (data.fromUser.id != userInfo.user_id) {
              const contact = msgStore.getContact(data.toContactId);
              this.playSound();
            }
            this.appendMessage(res, "tempChat");
            break;
          // 设置群管理员
          case "setManager":
          case "addGroupUser":
          case "removeUser":
            msgStore.updateContacts({
              id: data.group_id,
              avatar: data.avatar,
            });
            uni.$emit("updateGroup", res);
            break;
          // 修改群组名称
          case "editGroupName":
            msgStore.updateContacts({
              id: data.id,
              displayName: data.displayName,
            });
            break;
          case "removeGroup":
            msgStore.deleteContacts({
              id: data.group_id,
            });
            break;
          // 发布公告
          case "setNotice":
            msgStore.updateContacts({
              id: data.group_id,
              notice: data.notice,
            });
            break;
          // 群聊设置
          case "groupSetting":
            msgStore.updateContacts({
              id: data.group_id,
              setting: data.setting,
            });
            break;
          case "appendContact":
            msgStore.appendContacts(data);
            break;
          case "webrtc":
            let platform = "h5";
            //#ifdef H5
            platform = "h5";
            //#endif
            //#ifdef APP-PLUS
            platform = "app";
            //#endif

            //群语音
            if (data.is_group == 1) {
              const group_webrtc_user = data.group_webrtc_user ?? [];
              if (data.extends.event == "calling") {
                console.log("------------群语音--------------");
                const userInfo = uni.getStorageSync("userInfo");

                //所有通知到的用户ID -- 包括自己
                const usersID = group_webrtc_user.map((item) => Number(item.user_id));

                if (!usersID.includes(Number(userInfo.user_id))) {
                  console.log("当前通话中没有自己，return");
                  return;
                }

                const toUsers = group_webrtc_user.filter(
                  (item) => Number(item.user_id) === Number(userInfo.user_id) && Number(item.status) != 1
                );

                const call_user_id = toUsers.map((item) => item.user_id);

                this.appendMessages(res, toUsers);

                const allroutes = getCurrentPages();

                const cureentRoute = allroutes[allroutes.length - 1].route;

                // 如果当前已经在通话中,通知对方忙线中
                if (cureentRoute == "pages/message/call2") {
                  // console.log('------------通知对方忙线中--------------');
                  // this.$api.msgApi.sendToGroupMsg({
                  //   toContactId: data.toContactId,
                  //   type: data.extends.type,
                  //   event: 'busy',
                  //   status: data.extends.status,
                  //   code: 907,
                  //   id: data.id,
                  //   msg_id: data.msg_id
                  // });
                } else {
                  // 小程序不支持音视频聊天
                  //#ifdef APP-PLUS || H5
                  // uni.navigateTo({
                  //   url:
                  //     "/pages/message/call2?msg_id=" +
                  //     data.id +
                  //     "&type=" +
                  //     data.extends.type +
                  //     "&status=" +
                  //     data.extends.status +
                  //     "&id=" +
                  //     data.fromUser.user_id +
                  //     "&name=" +
                  //     data.fromUser.realname +
                  //     "&avatar=" +
                  //     encodeURI(data.fromUser.avatar) +
                  //     "&group_id=" +
                  //     data.toUser +
                  //     "&call_user_id=" +
                  //     call_user_id +
                  //     "&toContactId=" +
                  //     data.toContactId,
                  // });
                  //#endif
                }
              } else if (data.extends.event == "joinRtc") {
                uni.$emit("group_webrtc_user", group_webrtc_user);
              } else {
                uni.$emit("webrtcConn", data);
              }

              return;
            }

            if (data.fromUser.id == userInfo.user_id) {
              // 挂断的情况下解锁webrtc
              if ([902, 903, 905, 906, 907].includes(parseInt(data.extends.code))) {
                msgStore.webrtcLock = false;
              }
              // 如果是当前设备发出的消息则不处理
              if (data.extends.isMobile == 1 || data.extends.event == "calling") {
                if (data.extends.event == "calling") {
                  this.appendMessage(res);
                }
                return;
              }
            }

            // 如果是多端在线,要将在通话中的用户锁定
            if (data.extends.event == "offer" || data.extends.event == "answer") {
              msgStore.webrtcLock = true;
            } else if (data.extends.event == "hangup") {
              msgStore.webrtcLock = false;
            }

            //普通的一对一通话
            if (data.extends.event == "calling") {
              console.log("普通的一对一通话");
              this.appendMessage(res);
              const allroutes = getCurrentPages();
              const cureentRoute = allroutes[allroutes.length - 1].route;

              // 如果当前已经在通话中,通知对方忙线中
              if (cureentRoute == "pages/message/call") {
                this.$api.msgApi.sendToMsg({
                  toContactId: data.fromUser.user_id,
                  type: data.extends.type,
                  event: "busy",
                  status: data.extends.status,
                  code: 907,
                  id: data.id,
                  msg_id: data.msg_id,
                });
              } else {
                // 小程序不支持音视频聊天
                //#ifdef APP-PLUS || H5
                uni.navigateTo({
                  url:
                    "/pages/message/call?msg_id=" +
                    data.id +
                    "&type=" +
                    data.extends.type +
                    "&status=" +
                    data.extends.status +
                    "&id=" +
                    data.fromUser.user_id +
                    "&name=" +
                    data.fromUser.realname +
                    "&avatar=" +
                    encodeURI(data.fromUser.avatar),
                });
                //#endif
              }
            } else {
              uni.$emit("webrtcConn", data);
            }
            break;
          default:
            break;
        }
      });
      // 错误时做些什么
      uni.$on("connectError", () => {
        this.connect = false;
        this.scoketError = true;
        uni.$emit("socketStatus", false);
      });
    },
    //创建通知
    createMessage(data) {
      const id = data.toContactId ? data.toContactId : "";
      let content = data.content;

      if (data.type === "text") {
        content = data.content;
      } else if (data.type === "location") {
        content = "[位置信息]";
      } else if (data.type === "usercard") {
        content = "[名片]";
      } else if (data.type === "connectdragon") {
        content = `[接龙]`;
      } else {
        content = "新消息";
      }

      uni.createPushMessage({
        title: data.fromUser?.displayName ?? "新消息",
        content,
        payload: { toContactId: id },
        sound: "system",
        cover: true,
        when: new Date(),
      });
    },
    appendMessages(data, toUsers) {
      let contacts = msgStore.contacts;

      if (toUsers.length) {
        let contact = this.$util.findArray(contacts, Number(toUsers.user_id));

        if (contact) {
          contact.lastContent = data.content;
          contact.lastSendTime = data.sendTime;
          contact.type = data.type;
          contact.unread += addUnread;
          // 更新联系人信息
          msgStore.updateContacts(contact);
        }
      }
    },
    appendMessage(res, type) {
      let data = res.data;

      if (data.toContactId == "system") {
        // 系统消息只需要把未读数增加一
        msgStore.$patch({
          sysUnread: (msgStore.sysUnread += 1),
        });
      } else {
        let contacts = msgStore.contacts;
        let toUser = data.toContactId;
        // 判断是否是自己,自己发的看接收人是谁，去更新接受人的信息
        var userInfo = uni.getStorageSync("userInfo");
        let addUnread = 1;
        // 自己发送的不需要加
        if (data.fromUser.id == userInfo.user_id) {
          addUnread = 0;
        }
        if (data.toContactId == userInfo.user_id) {
          toUser = data.toUser;
        }
        let contact = this.$util.findArray(contacts, toUser);
        if (contact) {
          contact.lastContent = data.content;
          contact.lastSendTime = data.sendTime;
          contact.type = data.type;
          contact.unread += addUnread;

          data.call_user_ids &&
            data.call_user_ids.length &&
            data.call_user_ids.includes(userInfo.user_id) &&
            (contact.call_user_ids = {
              id: data.call_user_ids ?? [],
              msg_id: data.id,
            });

          // 更新联系人信息
          contact.change_hide && delete contact.change_hide;
          msgStore.updateContacts(contact);
        } else {
          let newContact = {
            id: data.toContactId,
            displayName: data.fromUser.displayName,
            avatar: data.fromUser.avatar,
            lastContent: data.content,
            lastSendTime: data.sendTime,
            is_group: data.is_group,
            identity: 0,
            is_top: 0,
            dep_id: 0,
          };

          if (type === "tempChat") {
            newContact["unread"] += addUnread;
            newContact["group_id"] = data.group_id;
            newContact["tempChat"] = true;
          }

          contacts.unshift(newContact);
          msgStore.initContacts(contacts);
        }
        msgStore.catchSocketAction(res);
      }
    },
    playSound() {
      let setting = uni.getStorageSync("appSetting") ?? "";
      if (setting.voiceStatus) {
        let _this = this;
        // _this.playing = true
        const innerAudioContext = uni.createInnerAudioContext();
        innerAudioContext.autoplay = true;
        innerAudioContext.src = "https://im-file.jwbl.top/audio/ding.mp3";
        innerAudioContext.onError((res) => {
          //如果音频没有正常播放
        });
        innerAudioContext.onStop((res) => {
          // _this.playing=false
          _this.$forceUpdate();
        });
      }
      if (setting.vibrateStatus) {
        uni.vibrateLong({
          success: function () {
            console.log("手机震动");
          },
        });
      }
    },
    register() {
      //注册
      keepAlive.register(
        {
          channelId: "畅了",
          channelName: "畅了",
          title: "畅了",
          content: "畅了运行中",
        },
        (res) => {
          console.log("注册keepAlive", res);
        }
      );
    },
    isRunning() {
      //是否正在运行
      keepAlive.isRunning((res) => {
        if (!res.isRunning) {
          this.restart();
        }
      });
    },
    restart() {
      //重启
      keepAlive.restart((res) => {
        console.log("重启保活", res);
      });
    },
    unregister() {
      //注销
      keepAlive.unregister((res) => {
        console.log(res);
        uni.showToast({
          title: res.msg,
          icon: "none",
          duration: 3000,
        });
      });
    },
    whiteList() {
      //获取并打开白名单
      keepAlive.whiteList(
        {
          isDialog: true,
          reason: "轨迹服务",
          whiteType: 0,
        },
        (res) => {
          console.log(res);
          uni.showToast({
            title: res.msg,
            icon: "none",
            duration: 3000,
          });
        }
      );
    },
    openWhiteList() {
      //打开白名单
      try {
        var list = JSON.parse(this.dataResult);
        keepAlive.openWhiteList(
          {
            isDialog: true,
            reason: "轨迹服务",
            type: list[0].type,
          },
          (res) => {
            console.log(res);
            uni.showToast({
              title: res.msg,
              icon: "none",
              duration: 3000,
            });
          }
        );
      } catch (e) {
        uni.showToast({
          title: "请先获取有效的白名单项",
          icon: "none",
          duration: 3000,
        });
      }
    },
    getWhiteList() {
      //获取白名单项
      keepAlive.getWhiteList(
        {
          whiteType: 0,
        },
        (res) => {
          console.log(res);
          this.dataResult = res.data ? JSON.stringify(res.data) : "";

          uni.showToast({
            title: res.msg,
            icon: "none",
            duration: 3000,
          });
        }
      );
    },
  },
  onHide: function () {
    this.appStatus = false;
  },
};
</script>

<style lang="scss">
@import url("static/css/iconfont.css");
@import url("static/fonts/font0/iconfont.css");
@import url("static/fonts/font1/iconfont.css");
@import url("static/fonts/font2/iconfont.css");
@import url("static/css/main.css");
@import url("static/css/icon.css");
@import url("static/css/reset.css");
/*每个页面公共css */
@import "@/uni_modules/uni-scss/index.scss";
/* #ifndef APP-NVUE */
@import "@/static/customicons.css";
@import "@/static/css/common.scss";
// 设置整个项目的背景色
page {
  background-color: #efefef;
}

:deep(.cell-2) {
  margin-top: 16rpx;
}

.ceshi {
  position: fixed;
  top: 100rpx;
  color: red;
  z-index: 9999;
}

/* #endif */
.example-info {
  font-size: 14px;
  color: #333;
  padding: 10px;
}
// view {
//   display: block;
// }
uni-modal {
  z-index: 3000;
}
uni-image div {
  width: 100%;
  height: 100%;
}
image,
uni-image {
  overflow: hidden;
}
uni-image,
img,
image {
  box-sizing: border-box;
  display: block;
}
input {
  font-size: calc(var(--amplified_base) * 16px);
  line-height: calc(var(--amplified_base) * 1.4em);
}

.uni-checkbox-input svg {
  transform: translate(-50%, -48%) scale(1) !important;
}
uni-toast,
.uni-toast {
  z-index: 3000 !important;
}

uni-system-choose-location,
.uni-system-choose-location {
  z-index: 2222 !important;
}
</style>
